<template>
  <div class="top-actions">
    <!-- #region 左侧工具栏 -->
    <div class="operation-toolbar">
      <el-tooltip effect="dark" content="开启框选" placement="bottom">
        <i class="iconfont icon-gateway" :class="{ checked: isGateway }" @click="changeGateway" />
      </el-tooltip>
      <el-tooltip effect="dark" content="上一步" placement="bottom">
        <i class="iconfont icon-undo" :class="{ disabled: !historyCanUndo }" @click="undoHandler" />
      </el-tooltip>
      <el-tooltip effect="dark" content="下一步" placement="bottom">
        <i class="iconfont icon-redo" :class="{ disabled: !historyCanRedo }" @click="redoHandler" />
      </el-tooltip>
      <el-tooltip effect="dark" content="导入" placement="bottom">
        <i class="iconfont icon-import" @click="showImportBox = true" />
      </el-tooltip>
      <el-tooltip effect="dark" content="导入图片" placement="bottom">
        <el-upload
          ref="elUpload" :action="imageAction" :data="{
            customerNo: this.$route.query.customerNo,
            type: '1',
            downloadId: this.$store.state.sensorsStore.downloadId
          }" :headers="headers" :show-file-list="false" :limit="1" :before-upload="beforeUpload"
          :on-success="handleImageSuccess"
        >
          <i class="iconfont icon-shangchuantupian" />
        </el-upload>
      </el-tooltip>
      <el-tooltip effect="dark" content="保存" placement="bottom">
        <i class="iconfont icon-save" @click="saveHandler" />
      </el-tooltip>
    </div>
    <!-- #endregion -->

    <!-- #region 右侧工具栏 -->
    <div class="function-toolbar">
      <el-tooltip effect="dark" content="放大" placement="bottom">
        <i class="iconfont icon-zoom-out" @click="zoomOutHandler" />
      </el-tooltip>
      <el-tooltip effect="dark" content="缩小" placement="bottom">
        <i class="iconfont icon-zoom-in" @click="zoomInHandler" />
      </el-tooltip>
      <el-tooltip effect="dark" content="缩放到1:1" placement="bottom">
        <i class="iconfont icon-one-to-one" @click="zoomOneToOneHandler" />
      </el-tooltip>
      <el-tooltip effect="dark" content="缩放到适应屏幕" placement="bottom">
        <i class="iconfont icon-compress" @click="zoomCompressHandler" />
      </el-tooltip>
      <el-tooltip effect="dark" content="帮助" placement="bottom">
        <i class="iconfont icon-help" @click="showHelpBox = true" />
      </el-tooltip>
      <el-tooltip effect="dark" content="返回查看" placement="bottom">
        <i class="iconfont icon-fanhui" @click="goBack" />
      </el-tooltip>
    </div>
    <!-- #endregion -->

    <!-- #region 导入JSON数据 -->
    <el-dialog title="导入JSON数据" :visible.sync="showImportBox" append-to-body>
      <el-form :model="form" :rules="rules">
        <el-form-item prop="content">
          <el-input v-model="form.content" type="textarea" :autosize="{ minRows: 4, maxRows: 10 }" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showImportBox = false">
          取 消
        </el-button>
        <el-button type="primary" @click="fromJSONToGraph">
          确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- #endregion -->

    <!-- #region 帮助 -->
    <el-dialog :visible.sync="showHelpBox" append-to-body>
      <template #title>
        <p class="title">
          帮助
        </p>
      </template>
      <p class="sub-title">
        快捷方式
      </p>
      <div class="card">
        <p>复制：ctrl + c</p>
        <p>粘贴：ctrl + v</p>
        <p>上一步：ctrl + z</p>
        <p>下一步：ctrl + shift + z</p>
        <p>删除：delete / backspace（选中节点或边的情况下）</p>
        <p>保存：ctrl + shift + s</p>
      </div>
    </el-dialog>
    <!-- #endregion -->
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import { Loading } from 'element-ui'
export default {
  data () {
    return {
      isGateway: false,
      showImportBox: false,
      form: {
        content: ''
      },
      rules: {
        content: { required: true, message: '请输入数据', tirgger: 'blur' }
      },
      showHelpBox: false,
      imageAction: process.env.VUE_APP_BASE_URL + '/admin/ryHistoryCount/uploadMineMap',
      headers: {
        'X-Token': getToken()
      },
      loading: null
    }
  },
  computed: {
    graph () {
      return this.$store.state.graphStore.graph
    },
    historyCanUndo () {
      return this.$store.state.graphStore.historyCanUndo
    },
    historyCanRedo () {
      return this.$store.state.graphStore.historyCanRedo
    }
  },
  methods: {
    // 开启/关闭 框选功能
    changeGateway () {
      this.isGateway = !this.isGateway
      this.graph.togglePanning(!this.isGateway)
      this.graph.toggleRubberband(this.isGateway)
    },
    // 上一步
    undoHandler () {
      if (this.graph.canUndo()) {
        this.graph.undo()
      }
    },
    // 下一步
    redoHandler () {
      if (this.graph.canRedo()) {
        this.graph.redo()
      }
    },
    // 保存
    async saveHandler () {
      if (!this.loading) {
        this.loading = Loading.service()
      }
      const drawJson = JSON.stringify(this.graph.toJSON())
      const res = await this.$http.post('/monitor/draw/saveOrUpdateDraw', {
        customerNo: this.$route.query.customerNo,
        drawJson
      })
      if (res === '保存成功') {
        this.$message.success('保存成功')
      } else {
        this.$message.error('保存成功')
      }
      this.loading.close()
    },
    goBack () {
      this.$router.go(-1)
    },
    // 导入JSON数据
    fromJSONToGraph () {
      this.graph.fromJSON(JSON.parse(this.form.content))
      this.showImportBox = false
    },
    // 放大
    zoomOutHandler () {
      this.graph.zoom(0.1)
    },
    // 缩小
    zoomInHandler () {
      this.graph.zoom(-0.1)
    },
    // 缩放到1:1
    zoomOneToOneHandler () {
      this.graph.zoomTo(1)
      this.graph.centerContent()
    },
    // 缩放到自适应
    zoomCompressHandler () {
      this.graph.zoomToFit({ maxScale: 1.6 })
      this.graph.centerContent()
    },
    beforeUpload () {
      this.loading = Loading.service()
    },
    // 图片上传成功回调
    handleImageSuccess (res, file) {
      if (res.code === -1) {
        this.$message.warning('上传失败')
        this.$refs.elUpload.clearFiles()
        return
      }
      this.$store.commit('SET_DOWNLOAD_ID', res.data?.id)
      const url = `${process.env.VUE_APP_BASE_URL}/system/archives/preview/image/${res.data.archivesUrl}`
      let backgroundNode = this.graph.getCellById('backgroundNode')
      if (!backgroundNode) {
        backgroundNode = this.graph.addNode({
          shape: 'background-node',
          id: 'backgroundNode'
        })
      }
      const img = new Image()
      img.src = url
      img.onload = () => {
        backgroundNode.setProp({
          size: {
            width: img.width,
            height: img.height
          }
        })
        backgroundNode.setAttrs({
          image: {
            'xlink:href': url
          }
        })
        this.zoomCompressHandler()
        this.saveHandler()
        this.$refs.elUpload.clearFiles()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.top-actions {
  width: 100%;
  height: 40px;
  border: 1px solid #d9d9d9;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .operation-toolbar,
  .function-toolbar {
    padding: 0 5px;
    display: flex;
  }

  .iconfont {
    font-size: 16px;
    padding: 8px 5px;
    margin-left: 3px;
    color: #595959;

    &:hover,
    &.checked {
      background-color: #e0e0e0;
      color: #000;
      border-radius: 2px;
    }

    &.disabled {
      color: #eee;

      &:hover {
        background-color: transparent;
        color: #eee;
      }
    }

  }
}

:deep(.el-upload) {
  height: 100%;
  display: flex;
  align-items: center;
}

.title {
  font-size: 20px;
  font-weight: bold;
  margin: 0px;
}

.sub-title {
  margin-top: 0px;
  font-weight: bold;
  font-size: 16px;
}

.card {
  text-indent: 2em;
}
</style>
